//
//  YLFuncDetailTableViewController.m
//  YLFinanceService
//
//  Created by she1323 on 2017/8/25.
//  Copyright © 2017年 she1323. All rights reserved.
//  基金详情

#import "YLFuncDetailTableViewController.h"
#import "YLFuncDetailHeader.h"
#import "YLTitleIamgeListCell.h"
#import "YLTitleHeader.h"
#import "YLTitleAllowCell.h"
#import "YLGlobeHeader.h"
#import <Masonry.h>
#import "PXAlertView.h"
#import "YLFuncDetailViewModel.h"
#import "YLFuncListModel.h"

@interface YLFuncDetailTableViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) YLFuncDetailViewModel *detailViewModel;
@property (nonatomic, weak) YLFuncDetailHeader *header;

@property (nonatomic, weak) UIButton * appointmentButton;

@end

@implementation YLFuncDetailTableViewController

- (YLFuncDetailViewModel *)detailViewModel
{
    if (!_detailViewModel) {
        _detailViewModel = [[YLFuncDetailViewModel alloc] init];
        _detailViewModel.listModel = _model;
    }
    return _detailViewModel;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    
    [self racEvent];
    [self setUpUI];
}


- (void)setUpUI
{
    self.title = _model.productName;
   
    __weak typeof(self) weakSelf = self;
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:tableView];
    tableView.delegate = self;
    tableView.dataSource = self;
    
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.mas_equalTo(weakSelf.view);
        make.bottom.mas_equalTo(weakSelf.view).mas_offset(-44);
    }];
    
    
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    YLFuncDetailHeader *header = [[YLFuncDetailHeader alloc] initWithFrame:[YLFuncDetailHeader headerFrame]];
    _header = header;
    header.headerTitles = self.detailViewModel.detailHeaderTitles;
    tableView.tableHeaderView = header;
    
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YLTitleIamgeListCell class]) bundle:nil] forCellReuseIdentifier:[YLTitleIamgeListCell cellID]];
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YLTitleAllowCell class]) bundle:nil] forCellReuseIdentifier:[YLTitleAllowCell cellID]];
    
    
    UIButton * appointmentButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _appointmentButton = appointmentButton;
    [appointmentButton addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    appointmentButton.backgroundColor = YLLOrgColor;
    [appointmentButton setTitle:@"正在查询预约状态" forState:UIControlStateNormal];
    appointmentButton.userInteractionEnabled = NO;
    
    if (_model.establishmentStatue == 1) {
        appointmentButton.backgroundColor = [UIColor lightGrayColor];
        [appointmentButton setTitle:@"募集结束" forState:UIControlStateNormal];
    }
    
    [self.view addSubview:appointmentButton];
    [appointmentButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(tableView.mas_bottom);
        make.left.right.bottom.mas_equalTo(weakSelf.view);
    }];
    
    [[self.detailViewModel.requestCommand execute:nil] subscribeNext:^(id  _Nullable x) {
        [weakSelf appointmentStatus:weakSelf.detailViewModel.listModel.isReservation];
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetY = scrollView.contentOffset.y + 64;
    if (offsetY < 0) {
        _header.offsetY = offsetY;
    }

}

- (void)btnClick:(UIButton *)sender
{
    
    
   
    
    
    __weak typeof(self) weakSelf = self;
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否进行预约?" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"预约" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [[weakSelf.detailViewModel.appointmentCommand execute:nil] subscribeNext:^(id  _Nullable x) {
            
            [PXAlertView showAlertWithTitle:@"您已成功预约" message:@"您的专属理财师将会在一个工作日联系您" cancelTitle:@"知道了" completion:^(BOOL cancelled) {
                [weakSelf appointmentStatus:YES];
                
            }];
        }];
        
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertController addAction:okAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

// 设置预约状态
- (void)appointmentStatus:(BOOL)status
{
    if (status == YES) {
        _appointmentButton.backgroundColor = [UIColor lightGrayColor];
        [_appointmentButton setTitle:@"已预约" forState:UIControlStateNormal];
        _appointmentButton.userInteractionEnabled = NO;
    } else {
        _appointmentButton.backgroundColor = YLLOrgColor;
        [_appointmentButton setTitle:@"预约购买" forState:UIControlStateNormal];
        _appointmentButton.userInteractionEnabled = YES;
        
        if (_model.establishmentStatue == 1) {
            _appointmentButton.backgroundColor = [UIColor lightGrayColor];
            [_appointmentButton setTitle:@"募集结束" forState:UIControlStateNormal];
            _appointmentButton.userInteractionEnabled = NO;
        }
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.detailViewModel.detailLists.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    YLFuncDetailModelGroup *group = self.detailViewModel.detailLists[section];
    return group.detailLists.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = nil;
    YLFuncDetailModelGroup *group = self.detailViewModel.detailLists[indexPath.section];
    YLFuncDetailModel *model = group.detailLists[indexPath.row];
    
    if (!model.clickBlock) {
        YLTitleIamgeListCell *cell = [tableView dequeueReusableCellWithIdentifier:[YLTitleIamgeListCell cellID] forIndexPath:indexPath];
        cell.model = model;
        return cell;
        
    } else {
        YLTitleAllowCell *cell = [tableView dequeueReusableCellWithIdentifier:[YLTitleAllowCell cellID] forIndexPath:indexPath];
        cell.model = model;
        return cell;
    }
    return cell;
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return [YLTitleHeader new];
     }
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 60;
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    YLFuncDetailModelGroup *group = self.detailViewModel.detailLists[indexPath.section];
    YLFuncDetailModel *model = group.detailLists[indexPath.row];
    if (model.clickBlock) {
        model.clickBlock();
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}

- (void)racEvent
{
    [self.detailViewModel.callPhoneSubject subscribeNext:^(NSString *x) {
        NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", x];
        
        if (@available(iOS 11.0, *)) {
           [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
        } else {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
            });
        }
       
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            
        });
    }];
}
@end
